package com.example.smartmallserver.demos.web.controller;

import com.example.smartmallserver.demos.web.pojo.Cart;
import com.example.smartmallserver.demos.web.service.IndexService;
import com.example.smartmallserver.demos.web.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@CrossOrigin
@RestController
public class CartController {
    @Autowired
    IndexService indexService;
    @Autowired
    HttpSession session;
    @PostMapping("/cart/add")
    Result addCart(@RequestBody Cart cart){
        System.out.println(cart);
        cart.setUserId((Integer) session.getAttribute("id"));
        indexService.addCart(cart);
        return Result.success();
    }

    @GetMapping("/cart/list")
    Result getCartList(){
        List<Cart> cartList = indexService.getCartList(session.getAttribute("id"));
        Integer total = indexService.getCartCountById(session.getAttribute("id"));
        Map<String,Object> map = new HashMap<>();
        map.put("cartList",cartList);
        map.put("total",total);
        return Result.success(map);
    }

    @PostMapping("/cart/update")
    Result updadeCartCount(@RequestBody Cart cart){
        indexService.updadeCartCount(cart);
        return Result.success();
    }

    @PostMapping("/cart/clear")
    Result deleteCartById(@RequestBody List<Cart> cart){
        System.out.println("cart； "+cart);
        for (int i=0;i<cart.size();i++){
            indexService.deleteCartById(cart.get(i).getId());
        }
        return Result.success();
    }
}
